package bold.deposit;


import bold.storage.core.RecordList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Khai Loon
 * @version 2017/3/24 0024 下午 4:40
 */
public class TreeUtil {

    private static final String next = "nodes";

    /**
     * @return JSONObject 无限封装树
     */
    public static Map<String, Object> toTree(RecordList recordList) {
        return toTree(recordList, "0", null);
    }

    private static Map<String, Object> toTree(RecordList recordList, String markId, Map<String, Object> result) {
        if (recordList == null || recordList.size() == 0) {
            return null;
        }

        if (result == null) {
            result = new HashMap<>();
        }

        if (haveSon(recordList, markId)) {
            result.put(next, new ArrayList<>());
            for (Map<String, Object> map : recordList) {
                if (map.get("parent_id").toString().equals(markId)) {
                    Map<String, Object> newMap = new HashMap<>();
                    for (String key : map.keySet()) {
                        newMap.put(key, map.get(key));
                    }
                    ((List<Object>) result.get(next)).add(
                            toTree(recordList, newMap.get("id").toString(), newMap)
                    );
                }
            }
        }

        return result;
    }

    private static boolean haveSon(RecordList recordList, String markId) {
        for (Map<String, Object> map : recordList) {
            if (map.get("parent_id").toString().equals(markId)) {
                return true;
            }
        }
        return false;
    }

}
